<template>
 <el-drawer :model-value="props.showDrawer"
 @open="openDrawer"
  @close="cancelSubmit"
 >
    <template #header>
      <h4>角色权限配置</h4>
    </template>
    <template #default>
      <el-tree
      style="max-width: 600px"
      ref="treeRef"
      :data="treeData"
      show-checkbox
      default-expand-all
      node-key="id"
      :default-checked-keys="checkedKey"
      highlight-current
      :props="defaultProps"
  />
    </template>
   
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelSubmit">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import axios from 'axios'
import { ref, reactive, defineProps, getCurrentInstance, onMounted } from 'vue';
import { ElMessage } from "element-plus";

let treeData = ref()
let props  = defineProps(['showDrawer','rid'])
let treeRef = ref()
let checkedKey = ref()


const { proxy } = getCurrentInstance()
const emit = defineEmits(['update:showDrawer'])

const defaultProps = ref({
  children: 'children',
  label: 'name',
})
async function openDrawer(){
  const { data: res } = await proxy.$http.get("/menu/getMenuByRole",{params:{rid:props.rid}});
  console.log('res', res);
  if (res.code == 200) {
    checkedKey.value = res.data
  }
}
async function getTree(){
  const { data: res } = await proxy.$http.get("/menu/getList");
  console.log('res', res);
  if (res.code == 200) {
    treeData.value = res.data;
  }
}
function cancelSubmit(){
  emit("update:showDrawer",false)
  console.log('cancelSubmit')
  treeRef.value.setCheckedKeys([])
}
async function  submit(){
 let menuIds = treeRef.value.getCheckedKeys()
 const { data: res } = await proxy.$http.put("/menu/updatePermission",null,{params:{rid:props.rid,menuIds:menuIds.join(",")}});
  console.log('res', res);
  if (res.code == 200) {
      ElMessage({
      message: "保存成功",
      type: "success",
    });
  }

  cancelSubmit()
}


onMounted(()=>{
  getTree()
})
</script>
<style lang="less" scoped>

</style>